<template>
  <div class="app-container">
    <div class="page_header">{{productId?'编辑':'添加'}}产品</div>
    <el-col :span="12">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="formData.productName" placeholder="请输入产品名称" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="productTypeId">
          <el-select v-model="formData.productTypeId" placeholder="请选择产品分类" clearable :style="{width: '100%'}">
            <el-option v-for="type in protypeList" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品设置" prop="productSettingList">
          <el-checkbox-group v-model="formData.productSettingList" size="medium">
            <el-checkbox v-for="(item, index) in productSettingListOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <template v-if="formData.productSettingList.includes(1)">
          <el-form-item label="方案产品价格" prop="productFanPrice">
            <el-input v-model="formData.productFanPrice" placeholder="请输入方案产品价格" :maxlength="10" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="方案产品库存" prop="productFanStore">
            <el-input v-model="formData.productFanStore" placeholder="请输入方案产品库存" :maxlength="10" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
        </template>
        <template v-if="formData.productSettingList.includes(2)">
          <el-form-item label="普通产品价格" prop="productPtoPrice">
            <el-input v-model="formData.productPtoPrice" placeholder="请输入普通产品价格" :maxlength="10" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="普通产品库存" prop="productPtoStore">
            <el-input v-model="formData.productPtoStore" placeholder="请输入普通产品库存" :maxlength="10" clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="产品单位" prop="productUnit">
          <el-input v-model="formData.productUnit" placeholder="请输入产品单位" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="产品类型" prop="productFunList">
          <el-checkbox-group v-model="formData.productFunList" size="medium">
            <el-checkbox v-for="(item, index) in productFunListOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="上传图片" required>
          <el-upload
            ref="url"
            :file-list="urlfileList"
            :headers="urlHeaders"
            :action="urlAction"
            :limit="5"
            :before-upload="urlBeforeUpload"
            :on-success="handleFileSuccess"
            list-type="picture"
            accept="image/*"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的图片文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品介绍" prop="productTxt">
          <editor v-model="formData.productTxt" :min-height="192" />
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" :disabled="pending" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </div>
</template>

<script>
import { getProDetail, addPro, updatePro } from '@/api/product/pro'
import { getProtypeList } from '@/api/product/protype'
import { uploadUrl } from '@/settings.js'
import { getToken } from '@/utils/auth'
import Editor from '@/components/Editor'
export default {
  name: 'Proedit',
  components: {
    Editor
  },
  data() {
    return {
      formData: {
        productName: undefined,
        productTypeId: undefined,
        productSettingList: [],
        productFanPrice: undefined,
        productFanStore: undefined,
        productPtoPrice: undefined,
        productPtoStore: undefined,
        productUnit: undefined,
        productFunList: [],
        url: null,
        productTxt: ''
      },
      rules: {
        productName: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ],
        productTypeId: [
          {
            required: true,
            message: '请选择产品分类',
            trigger: 'change'
          }
        ],
        productSettingList: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个产品设置',
            trigger: 'change'
          }
        ],
        productFanPrice: [
          {
            required: true,
            message: '请输入方案产品价格',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        productFanStore: [
          {
            required: true,
            message: '请输入方案产品库存',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9]\d*$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        productPtoPrice: [
          {
            required: true,
            message: '请输入普通产品价格',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        productPtoStore: [
          {
            required: true,
            message: '请输入普通产品库存',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9]\d*$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        productUnit: [
          {
            required: true,
            message: '请输入产品单位',
            trigger: 'blur'
          }
        ],
        productFunList: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个产品类型',
            trigger: 'change'
          }
        ],
        productTxt: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },
      protypeList: [],
      productSettingListOptions: [
        {
          label: '方案产品',
          value: 1
        },
        {
          label: '普通产品',
          value: 2
        }
      ],
      productFunListOptions: [],

      urlAction: uploadUrl,
      urlHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      urlfileList: [],
      //
      pending: false
    }
  },
  computed: {
    productId() {
      return this.$route.query.id
    }
  },
  async created() {
    this.initTypeList()
    this.initProductFunListOptions()
  },
  async mounted() {
    if (this.productId) {
      try {
        const res = await getProDetail(this.productId)
        const { productName, productTypeId, productSettingList, productFanPrice, productFanStore, productPtoPrice, productPtoStore, productUnit, productFunList, productTxt, url } = res.data
        this.formData = { productName, productTypeId, productSettingList, productFanPrice, productFanStore, productPtoPrice, productPtoStore, productUnit, productFunList, productTxt, url }
        this.urlfileList = url.map((per) => {
          return {
            name: per.name,
            url: per.url,
            response: {
              data: per
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
    } else {
      this.resetForm()
    }
  },
  // 编辑类不缓存
  // async activated() {
  // },
  methods: {
    async initTypeList() {
      try {
        const res = await getProtypeList({
          pageNum: 1,
          pageSize: 100000
        })
        if (res.code === 200) {
          this.protypeList = res.rows
        }
      } catch (error) {
        console.log(error)
      }
    },
    async initProductFunListOptions() {
      try {
        const res = await this.getDicts('product_fun')
        if (res.code === 200) {
          this.productFunListOptions = res.data.map((per) => ({
            label: per.dictLabel,
            value: per.dictValue
          }))
        }
      } catch (error) {
        console.log(error)
      }
    },
    submitForm() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        if (this.$refs.url.uploadFiles.length === 0) {
          this.$message.error('请上传图片')
          return
        }

        this.formData.url = this.$refs['url'].uploadFiles.map((per) => per.response.data)

        this.pending = true
        try {
          const fetchFn = this.productId ? updatePro : addPro
          const res = await fetchFn({
            ...this.formData,
            productId: this.productId ? this.productId : undefined
          })
          if (res.code === 200) {
            this.msgSuccess(res.msg)
            this.$closeNowTagsView()
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$refs['url'].clearFiles()
    },
    urlBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 200) {
        const index = fileList.findIndex((per) => per.uid === file.uid)
        fileList.splice(index, 1)
        this.$message({ message: response.msg, type: 'error' })
      }
    }
  }
}
</script>

<style lang='scss'>
</style>

